﻿using yao.Entity;
using yao.Mvc;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Titan;

namespace yao.website.Controllers
{
    /// <summary>
    /// 订单
    /// </summary>
    public class PurchaseOrderController:BaseController
    {
        #region private
        private string GeneratePurchaseOrderNo()
        {
           Random random=  new Random();
           StringBuilder sb=new StringBuilder(DateTime.Now.ToString("yyMMdd"));
            for (var i = 0; i < 8; i++)
            {
                sb.Append(random.Next(0,9));
            }
            return sb.ToString();
        }

        private PurchaseOrderLines GetPurchaseOrderLines(long PurchaseOrderId)
        {
            #region PurchaseOrderLines 订单行
            int PurchaseOrderLineRow = 0;
            PurchaseOrderLines PurchaseOrderLines = new PurchaseOrderLines();
            if (int.TryParse(Request.Form["PurchaseOrderLineRow"], out PurchaseOrderLineRow))
            {
                for (var i = 0; i < PurchaseOrderLineRow; i++)
                {

                    decimal Quantity;
                    decimal.TryParse(Request.Form["Quantity_" + i], out Quantity);//数量

                    long ProductId = 0;
                    long.TryParse(Request.Form["ProductId_" + i], out ProductId);//商品ID

                    string ProductName = Request.Form["ProductName_" + i];//商品名称
                    string Unit = Request.Form["Unit_" + i];//单位

                    decimal Price;
                    decimal.TryParse(Request.Form["Price_" + i], out Price);//单价

                    decimal Amount;
                    decimal.TryParse(Request.Form["Amount_" + i], out Amount);//金额
                    if (Amount != Price * Quantity)
                    {
                        Amount = Price * Quantity;
                    }

                    string Remark = Request.Form["Remark_" + i];
                    string ProductNo = Request.Form["ProductNo_" + i];
                    string Barcode = Request.Form["Barcode_" + i];
                    string Spec = Request.Form["Spec_" + i];
                    string LotNo = Request.Form["LotNo_" + i];

                    long PurchaseOrderLineId;
                    long.TryParse(Request.Form["PurchaseOrderLineId_" + i], out PurchaseOrderLineId);

                    if (string.IsNullOrEmpty(ProductNo) || string.IsNullOrEmpty(LotNo) || Quantity <= 0 || Price <= 0)
                    {
                        continue;
                    }
                    PurchaseOrderLine PurchaseOrderLine = new PurchaseOrderLine
                    {
                        ProductNo = ProductNo,
                        ProductId = ProductId,
                        ProductName = ProductName,
                        Quantity = Quantity,
                        Unit = Unit,
                        Price = Price,
                        Amount = Amount,
                        Barcode = Barcode,
                        Spec = Spec,
                        LotNo = LotNo,
                        Remark = Remark,
                        PurchaseOrderId = PurchaseOrderId,
                        PurchaseOrderLineId = PurchaseOrderLineId
                    };
                    PurchaseOrderLines.Items.Add(PurchaseOrderLine);
                }
            }
            return PurchaseOrderLines;
            #endregion
        }

        private PurchaseOrderLines GetPurchaseOrderLines(IDbSession cn,long purchaseOrderId) {
            QueryExpression q = new QueryExpression();
            q.EntityType = typeof(PurchaseOrderLine);
            q.Selects.Add(PurchaseOrderLine_.PurchaseOrderId);
            q.Selects.Add(PurchaseOrderLine_.ProductName);//商品名称
            q.Selects.Add(PurchaseOrderLine_.ProductNo);//商品编号
            q.Selects.Add(PurchaseOrderLine_.LotNo);//商品编号
            q.Selects.Add(PurchaseOrderLine_.Spec);//规格
            q.Selects.Add(PurchaseOrderLine_.Unit);//单位
            q.Selects.Add(PurchaseOrderLine_.Quantity);//数量
            q.Selects.Add(PurchaseOrderLine_.Price);//单价
            q.Selects.Add(PurchaseOrderLine_.Amount);//金额
            q.Selects.Add(PurchaseOrderLine_.Remark);//备注
            q.Wheres.Add(PurchaseOrderLine_.PurchaseOrderId.TEqual(purchaseOrderId));
            PurchaseOrderLines purchaseOrderLines = new PurchaseOrderLines();
            cn.SelectCollection(purchaseOrderLines.Items, q);
            return purchaseOrderLines;
        }
        /// <summary>
        /// 修改商品表锁定数量，可用数量，总数量
        /// </summary>
        /// <param name="quantity"></param>
        /// <param name="productId"></param>
        private void UpdateProduct(IDbSession cn, decimal quantity, long productId)
        {
            MySqlCommand cmdProduct = new MySqlCommand("update Product set LockCount=LockCount+@LockCount where ProductId=@ProductId");
            cmdProduct.Parameters.AddWithValue("@LockCount", quantity);
            cmdProduct.Parameters.AddWithValue("@ProductId", productId);
            cn.ExecuteNonQuery(cmdProduct);
        }
        private void UpdateStoreProduct(IDbSession cn, decimal quantity, long productId, string lotNo, long storeId)
        {
            MySqlCommand cmdStoreProduct = new MySqlCommand("update StoreProduct set LockQuantity=LockQuantity+@LockQuantity where ProductId=@ProductId and LotNo=@LotNo and StoreId=@StoreId and QualityStyleId=1");
            cmdStoreProduct.Parameters.AddWithValue("@LockQuantity", quantity);
            cmdStoreProduct.Parameters.AddWithValue("@ProductId", productId);
            cmdStoreProduct.Parameters.AddWithValue("@LotNo", lotNo);
            cmdStoreProduct.Parameters.AddWithValue("@StoreId", storeId);
            cn.ExecuteNonQuery(cmdStoreProduct);
        }
        #endregion

        public ActionResult Index(int? t, int? p)
        {
            int pageIndex = p == null ? 1 : (int)p;
            ViewBag.PageIndex = pageIndex;

            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(PurchaseOrder);
                q.Selects.Add(PurchaseOrder_.PurchaseOrderId);
                q.Selects.Add(PurchaseOrder_.PurchaseOrderNo);
                q.Selects.Add(PurchaseOrder_.ProviderId);
                q.Selects.Add(PurchaseOrder_.Provider.CompanyName);
                q.Selects.Add(PurchaseOrder_.ContactName);
                q.Selects.Add(PurchaseOrder_.CreateTime);
                q.Selects.Add(PurchaseOrder_.OrderEmployeeId);
                q.Selects.Add(PurchaseOrder_.OrderEmployee.EmployeeName);
                q.Selects.Add(PurchaseOrder_.Phone);//联系电话
                q.Selects.Add(PurchaseOrder_.ActualAmount);//实际金额
                q.Selects.Add(PurchaseOrder_.IsCompleted);//是否结束
                q.Selects.Add(PurchaseOrder_.IsDraft);//是否草稿订单
                q.Selects.Add(PurchaseOrder_.DeliveryStatusId);//交货状态
                q.Selects.Add(PurchaseOrder_.SettleStatusId);//结款状态
                q.Wheres.Add(PurchaseOrder_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                if (t != null)
                {
                    switch (t)
                    {
                        case 1://草稿订单
                            q.Wheres.Add(PurchaseOrder_.IsDraft.TEqual(true));
                            break;
                        case 2://未交货
                            q.Wheres.Add(PurchaseOrder_.DeliveryStatusId.TEqual(1));
                            break;
                        case 3://未结款
                            q.Wheres.Add(PurchaseOrder_.SettleStatusId.TEqual(1));
                            break;
                        case 4://已结束
                            q.Wheres.Add(PurchaseOrder_.IsCompleted.TEqual(true));
                            break;
                        default:
                            break;
                    }
                }
                q.PageIndex = pageIndex;
                q.PageSize = 20;
                q.OrderBy(PurchaseOrder_.PurchaseOrderId.Desc);
                q.ReturnMatchedCount = true;
                PurchaseOrders PurchaseOrders = new PurchaseOrders();
                PurchaseOrders.TotalCount = cn.SelectCollection(PurchaseOrders.Items, q);
                return View(PurchaseOrders);
            }
        }

        public ActionResult Edit(long? id)
        {
            PurchaseOrder PurchaseOrder = new PurchaseOrder();
            if (id != null)
            {
                ViewBag.Title = "修改采购订单-" + id;
                PurchaseOrder.PurchaseOrderId = (long)id;
                #region 查询订单行表
                using (IDbSession cn = OpenSession())
                {
                    cn.Select(PurchaseOrder,PurchaseOrder_.ALL,PurchaseOrder_.OrderEmployee.EmployeeName,PurchaseOrder_.Provider.CompanyName, PurchaseOrder_.Store.StoreName);
                    PurchaseOrder.PurchaseOrderLines = GetPurchaseOrderLines(cn,PurchaseOrder.PurchaseOrderId);
                }
                #endregion
            }
            else {
                PurchaseOrder.PurchaseOrderNo = GeneratePurchaseOrderNo();
                PurchaseOrder.DeliveryTime = DateTime.Now.AddDays(1);//配送时间
                PurchaseOrder.PurchaseOrderLines = new PurchaseOrderLines();
            }
            return View(PurchaseOrder);
        }

        #region 修改订单
        [HttpPost]
        public ActionResult Edit(long? id, PurchaseOrder PurchaseOrder)
        {
            #region 验证
            Validate(PurchaseOrder, PurchaseOrder_.PurchaseOrderNo);
            Validate(PurchaseOrder, PurchaseOrder_.ProviderId);
            Validate(PurchaseOrder, PurchaseOrder_.OrderEmployeeId);
            #endregion

            PurchaseOrder.PurchaseOrderLines = new PurchaseOrderLines();
            if (!IsValid)
            {
                return View(PurchaseOrder);
            }

            using (IDbSession cn = OpenSession())
            {
                cn.BeginTransaction();
                try
                {
                    PurchaseOrder.CompanyId = CurrentEmployee.CompanyId;

                    //添加
                    if (id == null)
                    {
                        #region 添加
                        #region validate
                        ConditionExpressionCollection cs = new ConditionExpressionCollection();
                        cs.Add(PurchaseOrder_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                        cs.Add(PurchaseOrder_.PurchaseOrderNo.TEqual(PurchaseOrder.PurchaseOrderNo));
                        if (cn.Exists<PurchaseOrder>(cs))
                        {
                            AddFormError(PurchaseOrder_.PurchaseOrderNo, "订单编号不允许重复");
                        }
                        if (!IsValid) return View(PurchaseOrder);
                        #endregion

                        PurchaseOrder.CreateTime = DateTime.Now;

                        PurchaseOrder.DeliveryStatusId = DeliveryStatus.NonDelivery;//交货状态


                        PurchaseOrder.SettleedAmount = 0;//已结算金额
                        PurchaseOrder.UnSettleedAmount = PurchaseOrder.ActualAmount - PurchaseOrder.SettleedAmount;//未结算金额
                        #region 结算状态
                        if (PurchaseOrder.SettleedAmount <= 0)
                        {
                            PurchaseOrder.SettleStatusId = SettleStatus.UnSettleed;
                        }
                        if (PurchaseOrder.SettleedAmount > 0 && PurchaseOrder.UnSettleedAmount > 0)
                        {
                            PurchaseOrder.SettleStatusId = SettleStatus.SettleedPart;
                        }
                        if (PurchaseOrder.SettleedAmount > 0 && PurchaseOrder.UnSettleedAmount <= 0 && PurchaseOrder.SettleedAmount == PurchaseOrder.ActualAmount)
                        {
                            PurchaseOrder.SettleStatusId = SettleStatus.SettleedComplete;
                        }
                        #endregion


                        PurchaseOrder.IsCompleted = false;
                        if (PurchaseOrder.SettleStatusId == SettleStatus.SettleedComplete && PurchaseOrder.DeliveryStatusId == DeliveryStatus.DeliveryComplete)
                        {
                            PurchaseOrder.IsCompleted = true;
                        }

                        #region 修改客户表数据信息：应收款金额、未完成订单数量
                        MySqlCommand cmd = new MySqlCommand("update provider set AccountPayables=AccountPayables+@AccountPayables,NotCompletedOrderCount=NotCompletedOrderCount+@NotCompletedOrderCount,LatestOrderTime=@LatestOrderTime where ProviderId=@ProviderId");
                        cmd.Parameters.AddWithValue("@AccountPayables", PurchaseOrder.UnSettleedAmount);
                        cmd.Parameters.AddWithValue("@NotCompletedOrderCount", PurchaseOrder.IsCompleted ? 0 : 1);//未完成订单数量
                        cmd.Parameters.AddWithValue("@LatestOrderTime", PurchaseOrder.CreateTime);//最近订货时间
                        cmd.Parameters.AddWithValue("@ProviderId", PurchaseOrder.ProviderId);
                        cn.ExecuteNonQuery(cmd);
                        #endregion

                        cn.Insert(PurchaseOrder);

                        #region 添加订单行
                        foreach (PurchaseOrderLine PurchaseOrderLine in GetPurchaseOrderLines(PurchaseOrder.PurchaseOrderId).Items)
                        {
                            cn.Insert(PurchaseOrderLine);

                            #region 修改库存表锁定数量，库存数量
                            UpdateStoreProduct(cn, PurchaseOrderLine.Quantity, PurchaseOrderLine.ProductId, PurchaseOrderLine.LotNo, PurchaseOrder.StoreId);
                            #endregion

                            #region 修改商品表锁定数量，可用数量，总数量
                            UpdateProduct(cn, PurchaseOrderLine.Quantity, PurchaseOrderLine.ProductId);
                            #endregion
                        }
                        #endregion

                        #endregion
                    }
                    else
                    {
                        #region 修改
                        PurchaseOrder.PurchaseOrderId = id.Value;
                        #region validate
                        ConditionExpressionCollection cs = new ConditionExpressionCollection();
                        cs.Add(PurchaseOrder_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                        cs.Add(PurchaseOrder_.PurchaseOrderNo.TEqual(PurchaseOrder.PurchaseOrderNo));
                        cs.Add(PurchaseOrder_.PurchaseOrderId.TNotEqual(PurchaseOrder.PurchaseOrderId));
                        if (cn.Exists<PurchaseOrder>(cs))
                        {
                            AddFormError(PurchaseOrder_.PurchaseOrderNo, "订单编号不允许重复");
                        }
                        if (!IsValid) return View(PurchaseOrder);
                        #endregion

                        #region 查询老的订单信息
                        PurchaseOrder PurchaseOrderFromDB = new PurchaseOrder { PurchaseOrderId = PurchaseOrder.PurchaseOrderId };
                        cn.Select(PurchaseOrderFromDB, PurchaseOrder_.StoreId);
                        #endregion

                        cn.Update(PurchaseOrder, PurchaseOrder_.PurchaseOrderNo, PurchaseOrder_.ProviderId, PurchaseOrder_.OrderEmployeeId,
                                 PurchaseOrder_.ContactName, PurchaseOrder_.Phone, PurchaseOrder_.ActualAmount, PurchaseOrder_.DeliveryRemark, PurchaseOrder_.DeliveryStatusId, PurchaseOrder_.DeliveryTime);

                        #region 修改订单行
                        PurchaseOrderLines PurchaseOrderLines1 = GetPurchaseOrderLines(PurchaseOrder.PurchaseOrderId);
                        foreach (PurchaseOrderLine PurchaseOrderLine in PurchaseOrderLines1.Items)
                        {
                            if (PurchaseOrderLine.PurchaseOrderLineId > 0)
                            {
                                PurchaseOrderLine PurchaseOrderLineFromDB = new PurchaseOrderLine { PurchaseOrderLineId = PurchaseOrderLine.PurchaseOrderLineId };
                                cn.Select(PurchaseOrderLineFromDB);
                                if (PurchaseOrderLineFromDB.ProductId == PurchaseOrderLine.ProductId)//如果还是同一个商品
                                {
                                    //如果还是同一批号的
                                    if (PurchaseOrderLineFromDB.LotNo == PurchaseOrderLine.LotNo)
                                    {
                                        #region 修改库存表锁定数量，库存数量(同批号的)
                                        UpdateStoreProduct(cn,
                                            PurchaseOrderLine.Quantity - PurchaseOrderLineFromDB.Quantity,
                                            PurchaseOrderLine.ProductId,
                                            PurchaseOrderLine.LotNo,
                                            PurchaseOrder.StoreId);
                                        #endregion
                                    }
                                    else
                                    {
                                        #region 修改库存表锁定数量，库存数量(不同批号的)
                                        UpdateStoreProduct(cn, -PurchaseOrderLineFromDB.Quantity,
                                            PurchaseOrderLineFromDB.ProductId,
                                            PurchaseOrderLineFromDB.LotNo,
                                            PurchaseOrder.StoreId);
                                        UpdateStoreProduct(cn,
                                            PurchaseOrderLine.Quantity,
                                            PurchaseOrderLine.ProductId,
                                            PurchaseOrderLine.LotNo,
                                            PurchaseOrder.StoreId);
                                        #endregion
                                    }

                                    #region 修改商品表锁定数量，可用数量，总数量
                                    UpdateProduct(cn, PurchaseOrderLine.Quantity - PurchaseOrderLineFromDB.Quantity, PurchaseOrderLine.ProductId);
                                    #endregion
                                }
                                else
                                {
                                    #region 修改为另一个商品了

                                    #region 修改库存表锁定数量，库存数量
                                    UpdateStoreProduct(cn, -PurchaseOrderLineFromDB.Quantity, PurchaseOrderLineFromDB.ProductId, PurchaseOrderLineFromDB.LotNo, PurchaseOrderFromDB.StoreId);
                                    UpdateStoreProduct(cn, PurchaseOrderLine.Quantity, PurchaseOrderLine.ProductId, PurchaseOrderLine.LotNo, PurchaseOrder.StoreId);
                                    #endregion

                                    #region 修改商品表锁定数量，可用数量，总数量
                                    UpdateProduct(cn, -PurchaseOrderLineFromDB.Quantity, PurchaseOrderLineFromDB.ProductId);
                                    UpdateProduct(cn, PurchaseOrderLine.Quantity, PurchaseOrderLine.ProductId);
                                    #endregion

                                    #endregion
                                }

                                cn.Update(PurchaseOrderLine, PurchaseOrderLine_.ALL);
                            }
                            else
                            {
                                cn.Insert(PurchaseOrderLine);

                                #region 修改库存表锁定数量，库存数量
                                UpdateStoreProduct(cn, PurchaseOrderLine.Quantity, PurchaseOrderLine.ProductId, PurchaseOrderLine.LotNo, PurchaseOrder.StoreId);
                                #endregion

                                #region 修改商品表锁定数量，可用数量，总数量
                                UpdateProduct(cn, PurchaseOrderLine.Quantity, PurchaseOrderLine.ProductId);
                                #endregion
                            }
                        }

                        QueryExpression query = new QueryExpression();
                        query.EntityType = typeof(PurchaseOrderLine);
                        query.Selects.Add(PurchaseOrderLine_.PurchaseOrderLineId);
                        query.Selects.Add(PurchaseOrderLine_.Quantity);
                        query.Selects.Add(PurchaseOrderLine_.ProductId);
                        query.Selects.Add(PurchaseOrderLine_.LotNo);
                        query.Wheres.Add(PurchaseOrderLine_.PurchaseOrderId.TEqual(PurchaseOrder.PurchaseOrderId));
                        PurchaseOrderLines PurchaseOrderLines2 = new PurchaseOrderLines();
                        cn.SelectCollection(PurchaseOrderLines2.Items, query);
                        foreach (PurchaseOrderLine PurchaseOrderLine in PurchaseOrderLines2.Items)
                        {
                            if (PurchaseOrderLines1.Items.Where(p => p.PurchaseOrderLineId == PurchaseOrderLine.PurchaseOrderLineId).Count() <= 0)
                            {
                                cn.Delete(PurchaseOrderLine);
                                UpdateStoreProduct(cn, -PurchaseOrderLine.Quantity, PurchaseOrderLine.ProductId, PurchaseOrderLine.LotNo, PurchaseOrder.StoreId);
                                UpdateProduct(cn, -PurchaseOrderLine.Quantity, PurchaseOrderLine.ProductId);
                            }
                        }
                        #endregion

                        #endregion
                    }
                    cn.Commit();
                }
                catch (Exception ex)
                {
                    cn.Rollback();
                    throw new BusinessException(ex.Message);
                }
            }
            return new IframeResult(Url.Action("Edit"), Url.Action("Index"));
        }
        #endregion

        #region 订单详情
        public ActionResult Detail(long id)
        {
            PurchaseOrder purchaseOrder = new PurchaseOrder();
            if (id>0)
            {
                ViewBag.Title = "采购入库单详情-" + id;
                purchaseOrder.PurchaseOrderId = (long)id;
                using (IDbSession cn = OpenSession())
                {
                    cn.Select(purchaseOrder,PurchaseOrder_.ALL,PurchaseOrder_.OrderEmployee.EmployeeName,PurchaseOrder_.Provider.CompanyName,PurchaseOrder_.Store.StoreName);
                    ViewData["PurchaseOrderLines"] = GetPurchaseOrderLines(cn, purchaseOrder.PurchaseOrderId).Items;
                }
            }
            return View(purchaseOrder);
        }
        #endregion

        #region 删除
        [HttpPost]
        public ActionResult Delete(long id)
        {
            PurchaseOrder purchaseOrder = new PurchaseOrder { PurchaseOrderId = id };
            using (IDbSession cn = OpenSession())
            {
                try
                {
                    cn.BeginTransaction();

                    cn.Select(purchaseOrder, PurchaseOrder_.DeliveryStatusId, PurchaseOrder_.SettleStatusId);
                    if (purchaseOrder.DeliveryStatusId > DeliveryStatus.NonDelivery)
                    {
                        return LJson(false, "不能删除该订单，改订单已配送或者已配送完成");
                    }
                    if (purchaseOrder.SettleStatusId > SettleStatus.UnSettleed)
                    {
                        return LJson(false, "不能删除该订单，该订单已结算过或者部分结算");
                    }

                    cn.Delete(purchaseOrder);

                    #region 修改客户表数据信息：应收款金额、未完成订单数量

                    #region 获取最后下单时间
                    QueryExpression query = new QueryExpression();
                    query.EntityType = typeof(PurchaseOrder);
                    query.Selects.Add(PurchaseOrder_.CreateTime);
                    query.OrderBys.Add(PurchaseOrder_.CreateTime.Desc);
                    query.PageSize = 1;
                    query.PageIndex = 1;
                    PurchaseOrders salesOrders1 = new PurchaseOrders();
                    cn.SelectCollection(salesOrders1.Items, query);
                    DateTime? latestOrderTime = null;
                    if (salesOrders1.Items.Count > 0)
                    {
                        latestOrderTime = salesOrders1.Items[0].CreateTime;
                    }
                    #endregion

                    MySqlCommand cmd = new MySqlCommand("update Provider set AccountPayables=AccountPayables+@AccountPayables,NotCompletedOrderCount=NotCompletedOrderCount+@NotCompletedOrderCount,LatestOrderTime=@LatestOrderTime where ProviderId=@ProviderId");
                    cmd.Parameters.AddWithValue("@AccountPayables", -purchaseOrder.UnSettleedAmount);//应付款
                    cmd.Parameters.AddWithValue("@NotCompletedOrderCount", -1);//未完成订单数量
                    cmd.Parameters.AddWithValue("@LatestOrderTime", latestOrderTime);//最近订货时间
                    cmd.Parameters.AddWithValue("@ProviderId", purchaseOrder.ProviderId);
                    cn.ExecuteNonQuery(cmd);
                    #endregion

                    #region 删除订单行
                    foreach (PurchaseOrderLine salesOrderLine in GetPurchaseOrderLines(cn, purchaseOrder.PurchaseOrderId).Items)
                    {
                        cn.Delete(salesOrderLine);
                        UpdateProduct(cn, -salesOrderLine.Quantity, salesOrderLine.ProductId);
                        UpdateStoreProduct(cn, -salesOrderLine.Quantity, salesOrderLine.ProductId, salesOrderLine.LotNo, purchaseOrder.StoreId);
                    }
                    #endregion
                    cn.Commit();
                }
                catch (Exception ex)
                {
                    cn.Rollback();
                    return LJson(false, "删除失败：" + ex.Message);
                }
            }
            return LJson(true, "删除成功");
        }

        #endregion

        #region 采购入库
        public ActionResult PurchaseIn(int? p)
        {
            int pageIndex = p == null ? 1 : (int)p;
            ViewBag.PageIndex = pageIndex;

            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(PurchaseOrder);
                q.Selects.Add(PurchaseOrder_.PurchaseOrderId);
                q.Selects.Add(PurchaseOrder_.PurchaseOrderNo);//销售单号
                q.Selects.Add(PurchaseOrder_.ProviderId);//客户
                q.Selects.Add(PurchaseOrder_.Provider.CompanyName);//客户
                q.Selects.Add(PurchaseOrder_.ContactName);//收货人
                q.Selects.Add(PurchaseOrder_.OrderEmployeeId);//业务员ID
                q.Selects.Add(PurchaseOrder_.OrderEmployee.EmployeeName);//业务员ID
                q.Selects.Add(PurchaseOrder_.Phone);//联系电话
                q.Selects.Add(PurchaseOrder_.IsCompleted);//是否结束
                q.Selects.Add(PurchaseOrder_.DeliveryStatusId);//交货状态
                q.Selects.Add(PurchaseOrder_.SettleStatusId);//结款状态
                q.Wheres.Add(PurchaseOrder_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                q.Wheres.Add(PurchaseOrder_.DeliveryStatusId.TEqual(DeliveryStatus.NonDelivery));//交货状态是：未发货
                q.OrderBy(PurchaseOrder_.CreateTime.Asc);
                q.ReturnMatchedCount = true;
                q.PageIndex = pageIndex;
                q.PageSize = 8;
                PurchaseOrders PurchaseOrders = new PurchaseOrders();
                PurchaseOrders.TotalCount = cn.SelectCollection(PurchaseOrders.Items, q);
                return View(PurchaseOrders);
            }
        }

        [HttpPost]
        public ActionResult PurchaseOrderLine(long PurchaseOrderId)
        {
            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(PurchaseOrderLine);
                q.Selects.Add(PurchaseOrderLine_.PurchaseOrderId);
                q.Selects.Add(PurchaseOrderLine_.ProductId);
                q.Selects.Add(PurchaseOrderLine_.ProductName);
                q.Selects.Add(PurchaseOrderLine_.ProductNo);
                q.Selects.Add(PurchaseOrderLine_.Spec);
                q.Selects.Add(PurchaseOrderLine_.LotNo);
                q.Selects.Add(PurchaseOrderLine_.Quantity);
                q.Selects.Add(PurchaseOrderLine_.Price);
                q.Selects.Add(PurchaseOrderLine_.Amount);
                q.Selects.Add(PurchaseOrderLine_.Remark);
                q.Wheres.Add(PurchaseOrderLine_.PurchaseOrderId.TEqual(PurchaseOrderId));
                PurchaseOrderLines PurchaseOrderLines = new PurchaseOrderLines();
                cn.SelectCollection(PurchaseOrderLines.Items, q);
                return Json(PurchaseOrderLines);
            }
        }

        /// <summary>
        /// 出库
        /// </summary>
        /// <param name="PurchaseOrderId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PurchaseIn(long PurchaseOrderId)
        {
            using (IDbSession cn = OpenSession())
            {
                try {
                    cn.BeginTransaction();

                    #region 查询订单数据 和 订单行数据
                    PurchaseOrder PurchaseOrder = new PurchaseOrder { PurchaseOrderId = PurchaseOrderId };
                    cn.Select(PurchaseOrder, PurchaseOrder_.StoreId);

                    QueryExpression query = new QueryExpression();
                    query.EntityType = typeof(PurchaseOrderLine);
                    query.Selects.Add(PurchaseOrderLine_.Quantity);
                    query.Selects.Add(PurchaseOrderLine_.LotNo);
                    query.Selects.Add(PurchaseOrderLine_.ProductId);
                    query.Wheres.Add(PurchaseOrderLine_.PurchaseOrderId.TEqual(PurchaseOrderId));
                    PurchaseOrderLines PurchaseOrderLines = new PurchaseOrderLines();
                    cn.SelectCollection(PurchaseOrderLines.Items, query);
                    #endregion

                    foreach (PurchaseOrderLine PurchaseOrderLine in PurchaseOrderLines.Items)
                    {
                        #region 商品库存表
                        MySqlCommand cmdStoreProduct = new MySqlCommand("update StoreProduct set UseableQuantity=UseableQuantity+@UseableQuantity,LockQuantity=LockQuantity+@LockQuantity,Quantity=Quantity+@Quantity where ProductId=@ProductId and LotNo=@LotNo and StoreId=@StoreId");
                        cmdStoreProduct.Parameters.AddWithValue("@UseableQuantity", PurchaseOrderLine.Quantity);
                        cmdStoreProduct.Parameters.AddWithValue("@LockQuantity", -PurchaseOrderLine.Quantity);
                        cmdStoreProduct.Parameters.AddWithValue("@Quantity", PurchaseOrderLine.Quantity);
                        cmdStoreProduct.Parameters.AddWithValue("@ProductId", PurchaseOrderLine.ProductId);
                        cmdStoreProduct.Parameters.AddWithValue("@LotNo", PurchaseOrderLine.LotNo);
                        cmdStoreProduct.Parameters.AddWithValue("@StoreId",PurchaseOrder.StoreId);
                        cn.ExecuteNonQuery(cmdStoreProduct);
                        #endregion

                        #region 商品表
                        MySqlCommand cmdProduct = new MySqlCommand("update Product set LockCount=LockCount+@LockCount,UseableCount=UseableCount+@UseableCount,StoreCount=StoreCount+@StoreCount where ProductId=@ProductId");
                        cmdProduct.Parameters.AddWithValue("@LockCount", -PurchaseOrderLine.Quantity);
                        cmdProduct.Parameters.AddWithValue("@StoreCount",PurchaseOrderLine.Quantity);
                        cmdProduct.Parameters.AddWithValue("@UseableCount", PurchaseOrderLine.Quantity);
                        cmdProduct.Parameters.AddWithValue("@ProductId", PurchaseOrderLine.ProductId);
                        cn.ExecuteNonQuery(cmdProduct);
                        #endregion
                    }

                    #region 修改交货状态
                    PurchaseOrder.DeliveryStatusId = DeliveryStatus.DeliveryComplete;
                    cn.Update(PurchaseOrder, PurchaseOrder_.DeliveryStatusId);
                    #endregion

                    cn.Commit();
                    return LJson(true,"入库成功");
                }
                catch {
                    cn.Rollback();
                    return Json(false,"出库失败");
                }
            }
        }
        #endregion
    }
}
